package com.msda.rabbitmq;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msda.constant.MqConstant;
import com.msda.mapper.OrderMapper;
import com.msda.mapper.ReservationMapper;
import com.msda.pojo.entity.order.Order;
import com.msda.pojo.entity.order.Reservation;
import com.msda.service.room.OrderService;
import com.msda.service.room.RoomService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

import static com.msda.constant.MqConstant.*;
import static com.msda.utils.TimestampUtils.getDayLevelTimestamp;
import static com.msda.utils.TimestampUtils.getHourOfDay;

@Component
@Transactional
public class Listener {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private RoomService meetingRoomService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = DELAY_ORDER_QUEUE,durable = "true"),
            exchange = @Exchange(value = DELAY_EXCHANGE,delayed = "true",type = ExchangeTypes.TOPIC),
            key = DELAY_ORDER_ROUTINE_KEY))
    public void listenOrderPayStatus(MultiDelayMessage<String> msg) throws IllegalAccessException {
        String orderId = msg.getData();
        Order order = orderMapper.selectById(orderId);
        if(order == null || order.getPaymentStatus().equals("expired")){
            if(order != null){
                meetingRoomService.unLockRoom(order.getRoomId());
            }
            return;
        }
        if(order.getPaymentStatus().equals("paid")){
            return;
        }
        if(msg.hasNextDelay()){
            Long nextDelay = msg.removeNextDelay();
            rabbitTemplate.convertAndSend(DELAY_EXCHANGE,DELAY_ORDER_ROUTINE_KEY,msg,
                    new DelayMessageProcessor(nextDelay.intValue()));
            return;
        } else {
            order.setPaymentStatus("expired");
            orderMapper.updateById(order);
        }

    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "order.delay.queue",durable = "true"),
            exchange = @Exchange(value = DELAY_EXCHANGE,delayed = "true",type = ExchangeTypes.TOPIC),
            key = DELAY_RESERVATION_ROUTINE_KEY))
    public void listenReservationStatus(String msg) throws IllegalAccessException {
        System.out.println(msg);
        msg = "检查预订单状态！";
        long now = System.currentTimeMillis();
        List<String> reservationId = reservationMapper.searchCompletedReservation(getDayLevelTimestamp(now),getHourOfDay(now));
        if(!reservationId.isEmpty()){
            UpdateWrapper<Reservation> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("status","completed").in("id",reservationId);
            reservationMapper.update(null,updateWrapper);
        }
        rabbitTemplate.convertAndSend(DELAY_EXCHANGE,DELAY_RESERVATION_ROUTINE_KEY,msg,
                    new DelayMessageProcessor(120000));
    }

}
